package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.model.domain.Announcement;
import com.itheima.commons.model.domain.UserInfo;
import com.itheima.commons.model.mongo.Comment;
import com.itheima.commons.model.mongo.Users;
import com.itheima.commons.model.vo.*;
import com.itheima.dubbo.interfaces.AnnouncementApi;
import com.itheima.dubbo.interfaces.CommentApi;
import com.itheima.dubbo.interfaces.UsersApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 消息业务类
 */
@Service
public class IMService {

    @Autowired
    private MyCenterService myCenterService;

    @Reference
    private UsersApi usersApi;

    @Autowired
    private HuanXinService hxService;

    @Autowired
    private UserInfoService userInfoService;

    @Reference
    private AnnouncementApi announcementApi;

    @Reference
    private CommentApi commentApi;

    /**
     * 根据环信的用户名 查询 用户详情
     *
     * @param userName
     * @return
     */
    public UserInfoVo queryUserInfoByHxUserName(String userName) {
        UserInfo userInfo = userInfoService.findUserInfoByUserId(Convert.toLong(StrUtil.subAfter(userName, "_", true)));

        UserInfoVo userInfoVo = new UserInfoVo();
        // 用户的ID
        userInfoVo.setId(userInfo.getUserId());
        userInfoVo.setAvatar(userInfo.getLogo());
        userInfoVo.setNickname(userInfo.getNickName());
        userInfoVo.setBirthday(userInfo.getBirthday());
        userInfoVo.setAge(userInfo.getAge().toString());
        userInfoVo.setGender(userInfo.getSex() == 1 ? "man" : "woman");
        userInfoVo.setCity(userInfo.getCity());
        userInfoVo.setEducation(userInfo.getEdu());
        userInfoVo.setIncome(userInfo.getIncome());
        userInfoVo.setProfession(userInfo.getIndustry());
        userInfoVo.setMarriage(userInfo.getMarriage() == "已婚" ? 1 : 0);

        return userInfoVo;
    }


    /**
     * 删除好友
     *
     * @param friendId
     */
    public void remoeContactUser(Long friendId) {
        // 调用MongoDB删除两条记录
        usersApi.removeUser(UserThreadLocal.getUserId(), friendId);
        usersApi.removeUser(friendId, UserThreadLocal.getUserId());

        // 给环信发送请求
        hxService.removeUserFriend(UserThreadLocal.getUserId(), friendId);
    }

    /**
     * 添加好友
     *
     * @param friendId
     */
    public void contactUser(Long friendId) {
        // 先往好友表中添加两条记录
        Users users = new Users();
        users.setId(new ObjectId());
        users.setUserId(UserThreadLocal.getUserId());
        users.setFriendId(friendId);
        users.setDate(System.currentTimeMillis());
        usersApi.addUsers(users);

        users.setFriendId(UserThreadLocal.getUserId());
        users.setUserId(friendId);
        usersApi.addUsers(users);

        // 给环信发送消息 让环信把两人绑定为好友
        hxService.addUserFriend(UserThreadLocal.getUserId(), friendId);
    }

    /**
     * 查询好友列表
     *
     * @param page     分页页码
     * @param pageSize 页面条数
     * @param keyword  关键词的搜索  如果关键词不为空 我们要查询全部好友并且根据关键词过滤  如果没有关键词 我们做分页
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        // 所有好友列表
        List<Users> users = usersApi.findUsersByUserId(UserThreadLocal.getUserId(), page, pageSize, keyword);
        // 提取好友的id
        List<Long> friendIds = CollUtil.getFieldValues(users, "friendId", Long.class);
        // 查询UserInfo
        Map<Long, UserInfo> userInfoListByUserIds = userInfoService.findUserInfoListByUserIds(UserInfo.builder().nickName(keyword).build(), friendIds);

        // 开始拼凑VO对象
        List<UsersVo> vos = new ArrayList<>();
        for (UserInfo info : userInfoListByUserIds.values()) {
            UsersVo usersVo = new UsersVo();
            // 用户ID
            usersVo.setId(info.getUserId());
            // 环信ID
            usersVo.setUserId("HX_" + info.getUserId());
            usersVo.setAvatar(info.getLogo());
            usersVo.setNickname(info.getNickName());
            usersVo.setGender(info.getSex() == 1 ? "man" : "woman");
            usersVo.setAge(info.getAge());
            usersVo.setCity(StrUtil.subBefore(info.getCity(), "-", false));
            vos.add(usersVo);
        }

        return new PageResult(page, pageSize, 0L, vos);
    }

    /**
     * 查询谁评论了我的列表
     *
     * @param page
     * @param pageSize
     * @param commentType 1 点赞  2 评论  3 喜欢
     * @return
     */
    public PageResult queryCommentList(Integer page, Integer pageSize, int commentType) {
        // 查询点赞/评论/喜欢列表
        List<Comment> commentList = commentApi.queryCommentListByUserId(page, pageSize, UserThreadLocal.getUserId(), commentType);
        // 从这个列表中提取发布评论的人的id
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        // 查询发布评论的人的信息
        Map<Long, UserInfo> infoMap = userInfoService.findUserInfoListByUserIds(null, userIds);
        // 拼凑VO对象
        List<MessageCommentVo> voList = new ArrayList<>();
        for (Comment comment : commentList) {
            MessageCommentVo vo = new MessageCommentVo();
            UserInfo info = infoMap.get(comment.getUserId());
            vo.setId(info.getUserId().toString());
            vo.setAvatar(info.getLogo());
            vo.setNickname(info.getNickName());
            vo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));
            voList.add(vo);
        }

        return new PageResult(page, pageSize, 0L, voList);
    }

    /**
     * 查询系统公告列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        List<Announcement> announcementList = announcementApi.findAnnouncementByPage(page, pageSize);
        List<AnnouncementVo> announcementVoList = new ArrayList<>();
        for (Announcement announcement : announcementList) {
            AnnouncementVo vo = new AnnouncementVo();
            vo.setId(announcement.getId().toString());
            vo.setTitle(announcement.getTitle());
            vo.setDescription(announcement.getDescription());
            vo.setCreateDate(DateUtil.format(announcement.getCreated(), "yyyy-MM-dd HH:mm"));
            announcementVoList.add(vo);
        }
        return new PageResult(page, pageSize, 0L, announcementVoList);
    }
}